package com.rt.tmpt.utils;

import com.rt.tmpt.dto.PaginationDto;
import net.sf.json.JSONArray;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class JsonPaginationUtils {
	public static <T> String paginationToJson(PaginationDto<T> pagination){
		List<T> productDtoList = pagination.getRecordList();
		JSONArray jsonArray1 = JSONArray.fromObject(productDtoList);
		String jsonList = jsonArray1.toString();
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		sb.append("\"total\":").append(pagination.getTotalRecordCount()).append(",");
		sb.append("\"rows\":");
		sb.append(jsonList);

		//合计
		Map<String,String> sumData = pagination.getSumData();
		Set<String> keySet = sumData.keySet();
		if(keySet.size()>0){
			sb.append(",\"footer\":");
			sb.append("[{");
			for(String key:keySet){
				sb.append("\"").append(key).append("\"").append(":").append("\"").append(sumData.get(key)).append("\"").append(",");
			}
			sb.delete(sb.length()-1, sb.length());
			sb.append("}]");
		}
		sb.append("}");
		String result = sb.toString();
		return result;
	}
	
	public static void responseWriter(HttpServletResponse response, String result){
		System.out.println("result:"+result);
		response.setCharacterEncoding("UTF-8");
		try {
			PrintWriter pw = response.getWriter();
			pw.write(result);
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void responseWriter(HttpServletResponse response, String result, String charset){
		response.setCharacterEncoding(charset);
		try {
			PrintWriter pw = response.getWriter();
			pw.write(result);
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	//起止日期逻辑不通
	public static boolean checkDateResponseWriter(String dateStart, String dateEnd, HttpServletResponse response){
		if(dateStart!= null && dateStart.trim() != "" && dateEnd!= null && dateEnd.trim() != ""){
			long dateStartLong = DateTool.string2Date(dateStart, "yyyy-MM-dd").getTime();
			long dateEndLong = DateTool.string2Date(dateEnd, "yyyy-MM-dd").getTime();
			if(dateStartLong>dateEndLong){
				//date error这段字符不要去了，和condition.jsp中有关
				JsonPaginationUtils.responseWriter(response, "起止日期逻辑不通:date error");
				return true;
			}
		}
		return false;
	}
}
